package guda.screenshot.biz;

import com.alibaba.fastjson.JSON;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by well on 2014/12/30.
 */
public class LoginBiz {
    private String host = "http://v.m1959.com";
    //private String host = "http://localhost:9999";
    private String login_url = host + "/login.json";
    private String post_url = host + "/buyer/upload.json";
    CloseableHttpClient httpclient = HttpClients.createDefault();
    private String user;
    private String password;
    private String taskId;

    public LoginBiz(String user,String password,String taskId){
        this.user = user;
        this.password = password;
        this.taskId = taskId;
    }

    public Response login() {
        HttpPost httppost = new HttpPost(
                login_url);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("name", user));
        formparams.add(new BasicNameValuePair("password", password));
        formparams.add(new BasicNameValuePair("taskId", taskId));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            HttpResponse response;
            response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != 200) {
                return new Response(false,"服务端返回状态错误，code:" + response.getStatusLine().getStatusCode());
            }
            if (entity != null) {
                String resStr = EntityUtils.toString(entity, "UTF-8");
                Response res = JSON.parseObject(resStr, Response.class);
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            // httpclient.getConnectionManager().shutdown();
        }
        return new Response(false,"服务暂时不可用");
    }


    public Response post() {
        HttpPost post = new HttpPost(post_url + "?taskId=" + taskId);
        try {
            Robot robot = new Robot();

            BufferedImage screenShot = robot.createScreenCapture(
                    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteOut);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(screenShot);
            param.setQuality(0.5f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(screenShot);
            byte[] buf = byteOut.toByteArray();
            byteOut.close();


            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addBinaryBody("file",buf, ContentType.create("image/jpeg"),getName());
            HttpEntity build = multipartEntity.build();
            post.setEntity(build);

            HttpResponse response = httpclient.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == 401) {
                login();
            }
            if (HttpStatus.SC_OK == status) {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String resStr = EntityUtils.toString(responseEntity, "UTF-8");
                    Response res = JSON.parseObject(resStr, Response.class);
                    return res;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response();
    }

    public static String getName(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
        return dateFormat.format(new Date())+".jpg";
    }

    public static void main(String[] args) throws InterruptedException {
        LoginBiz loginBiz = new LoginBiz("buyer","1111","1");
        Response login = loginBiz.login();
        System.out.println(login.isSuccess());
        if(login.isSuccess()){
            Response post = loginBiz.post();
            System.out.println(post.isSuccess());
        }
        while(true) {
            Thread.sleep(5 * 1000);
            Response post = loginBiz.post();
            System.out.println(post.isSuccess());
        }
    }

    public String getTaskId() {
        return taskId;
    }

    public String getPassword() {
        return password;
    }

    public String getUser() {
        return user;
    }
}
